package org.cloud.admin.auth.service.impl;

import java.util.Arrays;
import java.util.List;

import org.cloud.admin.auth.holder.AppHolder;
import org.cloud.admin.auth.service.SysUserRoleService;
import org.cloud.common.util.MapUtils;
import org.cloud.module.common.dao.SysUserRoleDao;
import org.cloud.module.common.entity.SysUserRoleEntity;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 用户与角色对应关系
 * @author wangyuan
 * @since 2019年6月26日 下午11:16:49
 *
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

	@Override
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		//先删除用户与角色关系
		this.removeByMap(new MapUtils().put("user_id", userId));

		if(roleIdList == null || roleIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Long roleId : roleIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);
			sysUserRoleEntity.setCreatedUser(String.valueOf(AppHolder.getLoginedUserId()));
			sysUserRoleEntity.setUpdatedUser(String.valueOf(AppHolder.getLoginedUserId()));

			this.save(sysUserRoleEntity);
		}
	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		return baseMapper.queryRoleIdList(userId);
	}

	@Override
	public boolean deleteBatch(Long[] roleIds){
		QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
		
		queryWrapper.in("role_id", Arrays.asList(roleIds));
		
		return remove(queryWrapper);
	}

    @Override
    public boolean deleteBatchByUserIds(Long[] userIds) {
        QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
        
        queryWrapper.in("user_id", Arrays.asList(userIds));
        
        return remove(queryWrapper);
    }
}
